package com.blb.common.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @author lvtian
 * @date 2022/11/24 15:08
 */
public class CookieUtil {
    /**
     * 添加Cookie
     * @param response
     * @param key
     * @param value
     * @param setAge
     * @throws IOException
     */
    public static void saveCookie(HttpServletResponse response, String key, String value , int setAge) throws IOException {
        key = URLEncoder.encode(key, "UTF-8");
        value = URLEncoder.encode(value, "UTF-8");
        Cookie cookie = new Cookie(key, value);
        cookie.setMaxAge(setAge);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    /**
     * 读取Cookie
     * @param request
     * @param key
     * @return
     * @throws IOException
     */
    public static String readCookie(HttpServletRequest request, String key) throws  IOException {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            String name = URLDecoder.decode(cookie.getName(), "UTF-8");
            String value = URLDecoder.decode(cookie.getValue(), "UTF-8");
            if(key.equals(name)){
                return value;
            }
        }
        return null;
    }

    public static void removeCookie(HttpServletResponse response, String key) throws IOException{
        saveCookie(response,key,"",0);
    }
}
